package com.smiletrain.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;


import com.smiletrain.base.Caso;
import com.smiletrain.base.Caso.Fotografia;
import com.smiletrain.base.Usuario;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.text.Html;

public class Util {

	public static boolean createDirIfNotExists(String path) {
	    boolean ret = true;

	    File file = new File(Environment.getExternalStorageDirectory(), path);
	    if (!file.exists()) {
	        if (!file.mkdirs()) {
	            ret = false;
	        }
	    }
	    return ret;
	}
	
	public static boolean writeObject(String file, Object obj) {
		boolean res = false;
	    ObjectOutput out;
		try {
			File ffile = new File(file);
			ffile.createNewFile();
			
			FileOutputStream sfile = new FileOutputStream(file);
			out = new ObjectOutputStream(sfile);
			out.writeObject(obj);
		    out.close();
		    res = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return res;
	    
	}
	
	public static Object readObject(String file) {
	    ObjectInput out;
	    Object obj = null;
		try {
			out = new ObjectInputStream(new FileInputStream(file));
			obj = out.readObject();
		    out.close();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return obj;
	    
	}
	
	public static void sendEmail(Caso caso, Context context, String[] emailTo, String[] emailCC,
		    String subject, String emailText, List<String> filePaths) {
		
	    final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
	    
	    emailIntent.setType("text/html");
	    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
	    
	    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(emailText));
	    
	    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, emailTo);
	    emailIntent.putExtra(android.content.Intent.EXTRA_CC, emailCC);
	    
	    ArrayList<Uri> uris = new ArrayList<Uri>();
	    
	    for (String file : filePaths)
	    {
	        File fileIn = new File(file);
	        Uri u = Uri.fromFile(fileIn);
	        uris.add(u);
	    }
	    if(filePaths.size() != 0)
	    	emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
	    
	    context.startActivity(Intent.createChooser(emailIntent, "Enviar email..."));
	}

	public static int sendCaso(Usuario usuario, Caso caso) {
		
		try {			
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost postRequest = new HttpPost(Constantes.URL_SEND_CASO);
			
			MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
			
			reqEntity.addPart("usuario_id", new StringBody(usuario.getNombre()));
			reqEntity.addPart("socio", new StringBody(caso.getSocio()));
			reqEntity.addPart("hospital", new StringBody(caso.getHospital()));
			reqEntity.addPart("matricula", new StringBody(caso.getMatricula()));
			reqEntity.addPart("firmo", new StringBody(caso.getFirmo()));
			reqEntity.addPart("apellidos", new StringBody(caso.getApellidos()));
			reqEntity.addPart("nombre", new StringBody(caso.getNombre()));
			reqEntity.addPart("genero", new StringBody(caso.getGenero()));
			reqEntity.addPart("raza", new StringBody(caso.getRaza()));
			reqEntity.addPart("calle", new StringBody(caso.getCalle()));
			reqEntity.addPart("ciudad", new StringBody(caso.getCiudad()));
			reqEntity.addPart("provincia", new StringBody(caso.getProvincia()));
			reqEntity.addPart("pais", new StringBody(caso.getPais()));
			reqEntity.addPart("cp", new StringBody(caso.getCp()));
			reqEntity.addPart("telefono", new StringBody(caso.getTelefono()));
			reqEntity.addPart("movil", new StringBody(caso.getMovil()));
			reqEntity.addPart("otromovil", new StringBody(caso.getOtroMovil()));
			
			reqEntity.addPart("tutorapellidos", new StringBody(caso.getTutorapellidos()));
			reqEntity.addPart("tutornombre", new StringBody(caso.getTutornombre()));
			reqEntity.addPart("relacion", new StringBody(caso.getRelacion()));
			reqEntity.addPart("seentero", new StringBody(caso.getSeentero()));
			
			reqEntity.addPart("duracion", new StringBody(caso.getDuracion()));
			reqEntity.addPart("complicaciones", new StringBody(caso.getComplicaciones()));
			reqEntity.addPart("fumo", new StringBody(caso.getFumo()));
			reqEntity.addPart("compli", new StringBody(caso.getCompli()));
			reqEntity.addPart("alcohol", new StringBody(caso.getAlcohol()));
			reqEntity.addPart("hermanos", new StringBody(caso.getHermanos()));
			reqEntity.addPart("familiar", new StringBody(caso.getFamiliar()));
			
			reqEntity.addPart("fecha", new StringBody(caso.getFecha()));
			reqEntity.addPart("cirujia", new StringBody(caso.getCirujia()));
			reqEntity.addPart("tipo", new StringBody(caso.getTipo()));
			reqEntity.addPart("labioizq", new StringBody(caso.getLabioizq()));
			reqEntity.addPart("labioder", new StringBody(caso.getLabioder()));
			reqEntity.addPart("cavidadizq", new StringBody(caso.getCavidadizq()));
			reqEntity.addPart("cavidadder", new StringBody(caso.getCavidadder()));
			reqEntity.addPart("paladarizq", new StringBody(caso.getPaladarizq()));
			reqEntity.addPart("paladarder", new StringBody(caso.getPaladarder()));
			reqEntity.addPart("suaveizq", new StringBody(caso.getSuaveizq()));
			reqEntity.addPart("suaveder", new StringBody(caso.getSuaveder()));
			reqEntity.addPart("comentarios", new StringBody(caso.getComentarios()));
			reqEntity.addPart("deformidad", new StringBody(caso.getDeformidad()));
			reqEntity.addPart("antes", new StringBody(caso.getAntes()));
			reqEntity.addPart("corazon", new StringBody(caso.getCorazon()));
			reqEntity.addPart("orejas", new StringBody(caso.getOrejas()));
			reqEntity.addPart("lengua", new StringBody(caso.getLengua()));
			reqEntity.addPart("creret", new StringBody(caso.getCreret()));
			reqEntity.addPart("urinario", new StringBody(caso.getUrinario()));
			reqEntity.addPart("miembros", new StringBody(caso.getMiembros()));
			reqEntity.addPart("esqueleto", new StringBody(caso.getEsqueleto()));
			reqEntity.addPart("retmen", new StringBody(caso.getRetmen()));
			reqEntity.addPart("ojos", new StringBody(caso.getOjos()));
			reqEntity.addPart("dedos", new StringBody(caso.getDedos()));
			reqEntity.addPart("mandibula", new StringBody(caso.getMandibula()));
			reqEntity.addPart("nariz", new StringBody(caso.getNariz()));
			reqEntity.addPart("piel", new StringBody(caso.getPiel()));
			reqEntity.addPart("habla", new StringBody(caso.getHabla()));
			reqEntity.addPart("alergia", new StringBody(caso.getAlergia()));
			reqEntity.addPart("otrasalergias", new StringBody(caso.getOtrasalergias()));
			reqEntity.addPart("medicamentos", new StringBody(caso.getMedicamentos()));
			reqEntity.addPart("problemas", new StringBody(caso.getProblemas()));
			
			reqEntity.addPart("admicion", new StringBody(caso.getAdmicion()));
			reqEntity.addPart("fcirujia", new StringBody(caso.getFcirujia()));
			reqEntity.addPart("alta", new StringBody(caso.getAlta()));
			reqEntity.addPart("cirujano", new StringBody(caso.getCirujano()));
			reqEntity.addPart("anestesiologo", new StringBody(caso.getAnestesiologo()));
			reqEntity.addPart("anestesia", new StringBody(caso.getAnestesia()));
			reqEntity.addPart("tipooper", new StringBody(caso.getTipooper()));
			reqEntity.addPart("labio", new StringBody(caso.getLabio()));
			reqEntity.addPart("lateral", new StringBody(caso.getLateral()));
			reqEntity.addPart("paladar", new StringBody(caso.getPaladar()));
			reqEntity.addPart("com", new StringBody(caso.getCom()));
			reqEntity.addPart("muerte", new StringBody(caso.getMuerte()));
			reqEntity.addPart("comentariosadi", new StringBody(caso.getComentariosadi()));
			
			//reqEntity.addPart("", new StringBody(caso.get));
			
			postRequest.setEntity(reqEntity);
			
			String sResponse;
			
			HttpResponse response = httpClient.execute(postRequest);
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "UTF-8"));
			
			sResponse = reader.readLine();
			
			if(sResponse != null && sResponse.trim().startsWith(Constantes.RESPUESTA_ENVIO_CORRECTO)){
				String[] arres = sResponse.split(",");
				if(arres.length >= 2 && !arres[1].trim().equals(""))
					caso.setId(Integer.parseInt(arres[1].trim()));
				return Constantes.OK;
			} else {
				error = sResponse;
			}

		} catch (Exception e) {
			error = e.getCause().toString() + e.getMessage();
			return Constantes.ERROR;
		}
		
		return Constantes.NO;
		
	}

	public static int sendImage(String usuario, String caso, String param, String name, String image){
		ByteArrayOutputStream bosPr1;
		Bitmap bmpr1;
		ByteArrayBody babPre1 = null;
		
		String imgpr1 = image;
		
		try {
			
			if(!imgpr1.equals("")) {
				BitmapFactory.Options op = new BitmapFactory.Options();
				op.inJustDecodeBounds = true;
				int scale = 1;
				FileInputStream fd = new FileInputStream(imgpr1);

				BitmapFactory.decodeFileDescriptor(fd.getFD(), null, op);
				
				if (op.outHeight > Constantes.IMAGE_MAX_SIZE || op.outWidth > Constantes.IMAGE_MAX_SIZE) {
					double d = Math.pow(2, (int) Math.round(Math.log(Constantes.IMAGE_MAX_SIZE / (double) Math.max(op.outHeight, op.outWidth)) / Math.log(0.5)));
					scale = (int) d;
				}
				
				op = new BitmapFactory.Options();
				op.inSampleSize = scale;

				bmpr1 = BitmapFactory.decodeFileDescriptor(fd.getFD(),null,op);
				
				bosPr1 = new ByteArrayOutputStream();
				bmpr1.compress(CompressFormat.JPEG, 70, bosPr1);
				byte[] datapr1 = bosPr1.toByteArray();
				babPre1 = new ByteArrayBody(datapr1, name);
			}
			
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost postRequest = new HttpPost(Constantes.URL_SEND_IMAGE);
			
			MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
			
			//reqEntity.addPart("", new StringBody(caso.get));
			
			reqEntity.addPart("caso_id", new StringBody(caso));
			reqEntity.addPart("usuario_id", new StringBody(usuario));
			reqEntity.addPart("param", new StringBody(param));
			if(babPre1 != null)
				reqEntity.addPart(param, babPre1);
			
			postRequest.setEntity(reqEntity);
			
			String sResponse;
			
			HttpResponse response = httpClient.execute(postRequest);
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "UTF-8"));
			
			sResponse = reader.readLine();
			
			if(sResponse.trim().equals(Constantes.RESPUESTA_ENVIO_CORRECTO)){
				return Constantes.OK;
			} else {
				error = sResponse;
			}

		} catch (Exception e) {
			error = e.getCause().toString() + e.getMessage();
			return Constantes.ERROR;
		}
		
		return Constantes.NO;
	}

	public static int sendImage(String emailTo, String asunto, Usuario usuario, Caso caso) {
		
		Fotografia preFotos = caso.getPreFotos();
		Fotografia postFotos = caso.getPostFotos();
		
		String inter = "";
		String[] xinter = caso.getIntervencionNumerica().split(",");
		
		for(int i = 0 ; i < xinter.length ; i++){
			if(xinter[i].equals("0")){
				inter += "Cierre Primario de Labio Unilateral";
			} else if(xinter[i].equals("1")){
				inter += "Cierre Primario de Labio Bilateral";
			} else if(xinter[i].equals("2")){
				inter += "Correción Labial y/o Nasal";
			} else if(xinter[i].equals("3")){
				inter += "Cierre Primario del Paladar";
			} else if(xinter[i].equals("4")){
				inter += "Cierre Secundario del Paladar";
			} else if(xinter[i].equals("5")){
				inter += "Cierre de Fístula";
			} else if(xinter[i].equals("6")){
				inter += "Injerto Óseo Alveolar";
			}
			if(i != xinter.length - 1)
				inter += " / ";
		}
		
		
		ByteArrayOutputStream bosPr1, bosPr2, bosPs1, bosPs2;
		Bitmap bmpr1, bmpr2, bmps1, bmps2;
		ByteArrayBody babPre1 = null, babPre2 = null, babPost1 = null, babPost2 = null;
		
		String imgpr1 = preFotos.getPathImage1();
		String imgpr2 = preFotos.getPathImage2();
		String imgps1 = postFotos.getPathImage1();
		String imgps2 = postFotos.getPathImage2();
		
		try {			
			
			if(!imgpr1.equals("")) {
				BitmapFactory.Options op = new BitmapFactory.Options();
				op.inJustDecodeBounds = true;
				int scale = 1;
				FileInputStream fd = new FileInputStream(imgpr1);

				BitmapFactory.decodeFileDescriptor(fd.getFD(), null, op);
				
				if (op.outHeight > Constantes.IMAGE_MAX_SIZE || op.outWidth > Constantes.IMAGE_MAX_SIZE) {
					double d = Math.pow(2, (int) Math.round(Math.log(Constantes.IMAGE_MAX_SIZE / (double) Math.max(op.outHeight, op.outWidth)) / Math.log(0.5)));
					scale = (int) d;
				}
				
				op = new BitmapFactory.Options();
				op.inSampleSize = scale;

				bmpr1 = BitmapFactory.decodeFileDescriptor(fd.getFD(),null,op);
				
				bosPr1 = new ByteArrayOutputStream();
				bmpr1.compress(CompressFormat.JPEG, 70, bosPr1);
				byte[] datapr1 = bosPr1.toByteArray();
				babPre1 = new ByteArrayBody(datapr1, preFotos.getNameImage1());
			}
			
			if(!imgpr2.equals("")) {
				BitmapFactory.Options op = new BitmapFactory.Options();
				op.inJustDecodeBounds = true;
				int scale = 1;
				FileInputStream fd = new FileInputStream(imgpr2);

				BitmapFactory.decodeFileDescriptor(fd.getFD(), null, op);
				
				if (op.outHeight > Constantes.IMAGE_MAX_SIZE || op.outWidth > Constantes.IMAGE_MAX_SIZE) {
					double d = Math.pow(2, (int) Math.round(Math.log(Constantes.IMAGE_MAX_SIZE / (double) Math.max(op.outHeight, op.outWidth)) / Math.log(0.5)));
					scale = (int) d;
				}
				
				op = new BitmapFactory.Options();
				op.inSampleSize = scale;

				bmpr2 = BitmapFactory.decodeFileDescriptor(fd.getFD(),null,op);
				
				bosPr2 = new ByteArrayOutputStream();
				bmpr2.compress(CompressFormat.JPEG, 70, bosPr2);
				byte[] datapr2 = bosPr2.toByteArray();
				babPre2 = new ByteArrayBody(datapr2, preFotos.getNameImage2());
			}
			
			if(!imgps1.equals("")) {
				BitmapFactory.Options op = new BitmapFactory.Options();
				op.inJustDecodeBounds = true;
				int scale = 1;
				FileInputStream fd = new FileInputStream(imgps1);

				BitmapFactory.decodeFileDescriptor(fd.getFD(), null, op);
				
				if (op.outHeight > Constantes.IMAGE_MAX_SIZE || op.outWidth > Constantes.IMAGE_MAX_SIZE) {
					double d = Math.pow(2, (int) Math.round(Math.log(Constantes.IMAGE_MAX_SIZE / (double) Math.max(op.outHeight, op.outWidth)) / Math.log(0.5)));
					scale = (int) d;
				}
				
				op = new BitmapFactory.Options();
				op.inSampleSize = scale;

				bmps1 = BitmapFactory.decodeFileDescriptor(fd.getFD(),null,op);
				
				bosPs1 = new ByteArrayOutputStream();
				bmps1.compress(CompressFormat.JPEG, 70, bosPs1);
				byte[] dataps1 = bosPs1.toByteArray();
				babPost1 = new ByteArrayBody(dataps1, postFotos.getNameImage1());
			}
			
			if(!imgps2.equals("")) {
				BitmapFactory.Options op = new BitmapFactory.Options();
				op.inJustDecodeBounds = true;
				int scale = 1;
				FileInputStream fd = new FileInputStream(imgps2);

				BitmapFactory.decodeFileDescriptor(fd.getFD(), null, op);
				
				if (op.outHeight > Constantes.IMAGE_MAX_SIZE || op.outWidth > Constantes.IMAGE_MAX_SIZE) {
					double d = Math.pow(2, (int) Math.round(Math.log(Constantes.IMAGE_MAX_SIZE / (double) Math.max(op.outHeight, op.outWidth)) / Math.log(0.5)));
					scale = (int) d;
				}
				
				op = new BitmapFactory.Options();
				op.inSampleSize = scale;

				bmps2 = BitmapFactory.decodeFileDescriptor(fd.getFD(),null,op);
				
				bosPs2 = new ByteArrayOutputStream();
				bmps2.compress(CompressFormat.JPEG, 70, bosPs2);
				byte[] dataps2 = bosPs2.toByteArray();
				babPost2 = new ByteArrayBody(dataps2, postFotos.getNameImage2());
			}
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost postRequest = new HttpPost(Constantes.URL_SEND_IMAGE_MAIL);
			
			MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
			
			//reqEntity.addPart("", new StringBody(caso.get));
			
			reqEntity.addPart("usuario_id", new StringBody(usuario.getNombre()));
			
			reqEntity.addPart("inter", new StringBody(inter));
			
			reqEntity.addPart("nombre", new StringBody(caso.getPaciente().getNombres()));
			reqEntity.addPart("apellidos", new StringBody(caso.getPaciente().getApellidos()));
			reqEntity.addPart("genero", new StringBody(caso.getPaciente().isGenero()? "Hombre" : "Mujer"));
			
			reqEntity.addPart("socio", new StringBody(usuario.getSocio()));
			
			reqEntity.addPart("emailTo", new StringBody(emailTo));
			reqEntity.addPart("asunto", new StringBody(asunto));
			
			if(caso.getNumFotografias() == 1){
				if(babPre1 != null)
					reqEntity.addPart("prefoto1", babPre1);
				if(babPost1 != null)
					reqEntity.addPart("postfoto1", babPost1);
			} else if(caso.getNumFotografias() == 2) {
				if(babPre1 != null)
					reqEntity.addPart("prefoto1", babPre1);
				if(babPost1 != null)
					reqEntity.addPart("postfoto1", babPost1);
				if(babPre2 != null)
					reqEntity.addPart("prefoto2", babPre2);
				if(babPost2 != null)
					reqEntity.addPart("postfoto2", babPost2);
			}
			
			postRequest.setEntity(reqEntity);
			
			String sResponse;
			
			HttpResponse response = httpClient.execute(postRequest);
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "UTF-8"));
			
			sResponse = reader.readLine();
			
			if(sResponse.trim().equals(Constantes.RESPUESTA_ENVIO_CORRECTO)){
				return Constantes.OK;
			} else {
				error = sResponse;
			}

		} catch (Exception e) {
			error = e.getCause().toString() + e.getMessage();
			return Constantes.ERROR;
		}
		
		return Constantes.NO;
	}
	
	public static boolean buildZip(Caso caso) {
		String zipfile = Environment.getExternalStorageDirectory().getAbsolutePath() + 
				Constantes.ZIP_PATH + Constantes.ZIP_FILE;
		
		OutputStream os = null;
		InputStream is = null;
		ZipOutputStream zos = null;
		
		boolean res = false;
		
		try {
			if(generarCaso(caso)){
				os = new FileOutputStream(zipfile);
				zos = new ZipOutputStream(os);
				
				is = new FileInputStream(caso.getCsvFile());
				String filename = new File(caso.getCsvFile()).getName();
		        byte[] bytes = new byte[is.available()];
		        is.read(bytes);
		        ZipEntry entry = new ZipEntry(filename);
		        zos.putNextEntry(entry);
		        zos.write(bytes);
		        zos.closeEntry();
		        is.close();
		        
		        if(!caso.getPreFotos().getNameImage1().equals("")){
			        is = new FileInputStream(caso.getPreFotos().getPathImage1());
			        filename = "photo0.jpg";
			        bytes = new byte[is.available()];
			        is.read(bytes);
			        entry = new ZipEntry(filename);
			        zos.putNextEntry(entry);
			        zos.write(bytes);
			        zos.closeEntry();
			        is.close();
		        }
		        
		        if(!caso.getPostFotos().getNameImage1().equals("")){
			        is = new FileInputStream(caso.getPostFotos().getPathImage1());
			        filename = "photo1.jpg";
			        bytes = new byte[is.available()];
			        is.read(bytes);
			        entry = new ZipEntry(filename);
			        zos.putNextEntry(entry);
			        zos.write(bytes);
			        zos.closeEntry();
			        is.close();
		        }
		        
		        if(!caso.getPreFotos().getNameImage2().equals("")){
			        is = new FileInputStream(caso.getPreFotos().getPathImage2());
			        filename = "photo2.jpg";
			        bytes = new byte[is.available()];
			        is.read(bytes);
			        entry = new ZipEntry(filename);
			        zos.putNextEntry(entry);
			        zos.write(bytes);
			        zos.closeEntry();
			        is.close();
		        }
		        
		        if(!caso.getPostFotos().getNameImage2().equals("")){
			        is = new FileInputStream(caso.getPostFotos().getPathImage2());
			        filename = "photo3.jpg";
			        bytes = new byte[is.available()];
			        is.read(bytes);
			        entry = new ZipEntry(filename);
			        zos.putNextEntry(entry);
			        zos.write(bytes);
			        zos.closeEntry();
			        is.close();
		        }
		        
		        res = true;
		        
			} else {
				error = "No se genero el Archivo CSV";
				res = false;
			}
		} catch (Exception e) {
			error = e.getCause().toString() + e.getMessage();
			res = false;
		} finally {
			try {
				zos.close();
				is.close();
				os.close();
				caso.setZipFile(zipfile);
			} catch(Exception e) {
				error = e.getCause().toString() + e.getMessage();
				res = false;
			}
		}
		
		return res;
	}
	
	public static boolean generarCaso(Caso caso) {
		String file = Environment.getExternalStorageDirectory().getAbsolutePath() + 
				Constantes.ZIP_PATH + "Caso_" + caso.getId() + Constantes.FILE;
		
		File ffile = null;
		PrintWriter pw = null;
		
		boolean res = false;
		
		try{
			ffile = new File(file);
		    if(!ffile.exists())
		    	ffile.createNewFile();
		    
			pw = new PrintWriter(new FileWriter(file));
			pw.println("patientID@@@" + caso.getMatricula());
			pw.println("patientIDLoc@@@");
			pw.println("guardianConsent@@@" + (caso.getFirmo().equals("Si") ? "1" : "0"));
			pw.println("lastName@@@" + caso.getApellidos());
			pw.println("lastNameLoc@@@");
			pw.println("firstName@@@" + caso.getNombre());
			pw.println("firstNameLoc@@@");
			pw.println("middleName@@@");
			pw.println("middleNameLoc@@@"); //
			String day = caso.getNacimiento().split("/")[0];
			String month = caso.getNacimiento().split("/")[1];
			String year = caso.getNacimiento().split("/")[2];
			pw.println("dateOfBirthDay@@@" + day);
			pw.println("dateOfBirthMonth@@@" + month);
			pw.println("dateOfBirthYear@@@" + year); 
			pw.println("gender@@@" + (caso.getGenero().equals("Hombre") ? "M" : "F"));
			pw.println("race@@@" + (
					caso.getRaza().equals("Hispano") ?
							"7" :
							caso.getRaza().equals("Caucásico") ?
								"2" :
								caso.getRaza().equals("Asiático") ?
									"1" :
									caso.getRaza().equals("Africano") ?
										"3" :
										caso.getRaza().equals("Asiático Hindú") ?
											"4" :
											caso.getRaza().equals("Otro") ?
												"5" : "6" // mixed
						));
			pw.println("street1@@@" + caso.getCalle());
			pw.println("city@@@" + caso.getCiudad());
			pw.println("state1@@@" + caso.getProvincia());
			pw.println("zip@@@" + caso.getCp());
			pw.println("phone@@@" + caso.getTelefono());
			pw.println("mobile@@@" + caso.getMovil());
			pw.println("otherphone@@@" + caso.getOtroMovil());
			pw.println("country@@@" + caso.getPais());
			pw.println("partnerList@@@" + Util.getIDSocio(caso.getSocio()));
			pw.println("hospitalList@@@" + Util.getIDHospital(caso.getHospital()));
			pw.println("gFirstName@@@" + caso.getTutornombre());
			pw.println("gLastName@@@" + caso.getTutorapellidos());
			pw.println("relationship@@@" + (
					caso.getRelacion().equals("Padre") ?
							"2" :
							caso.getRelacion().equals("Madre") ?
								"1" :
								caso.getRelacion().equals("Abuelo") ?
									"3" :
									caso.getRelacion().equals("Abuela") ?
										"3" :
										caso.getRelacion().equals("Hermano") ?
											"4" :
											caso.getRelacion().equals("Hermana") ?
												"5" :
												caso.getRelacion().equals("Otro") ?
													"10" :
													caso.getRelacion().equals("Tía") ?
														"6" :
														caso.getRelacion().equals("Tío") ?
															"7" :
															caso.getRelacion().equals("Primo") ?
																"8" :
																caso.getRelacion().equals("Prima") ?
																	"8" :
																	caso.getRelacion().equals("Amigo") ?
																		"9" : "11"  // self
						));
			pw.println("knowAboutST@@@" + (
					caso.getSeentero().equals("Asociación") ?
							"1" :
							caso.getSeentero().equals("Hospital") ?
								"4" :
								caso.getSeentero().equals("Periódico / TV") ?
									"2" :
									caso.getSeentero().equals("Internet") ?
										"5" :
										caso.getSeentero().equals("Amigos / Conocidos") ?
											"3" :
											caso.getSeentero().equals("Otro") ?
												"6" : "0"
						));
			pw.println("pregnancyLength@@@" + (caso.getDuracion().equals("Nose") ? "0" : caso.getDuracion()));
			pw.println("lengthPregnancyUK@@@"); //
			pw.println("pregnancyComplication@@@" + (caso.getComplicaciones().equals("Si") ? "True" : caso.getComplicaciones().equals("No") ? "False" : "" ));
			pw.println("birthComplication@@@" + (caso.getCompli().equals("Si") ? "True" : caso.getCompli().equals("No") ? "False" : "" ));
			pw.println("motherSmoked@@@" + (caso.getFumo().equals("Si") ? "True" : caso.getFumo().equals("No") ? "False" : "" ));
			pw.println("motherAlcohol@@@" + (caso.getAlcohol().equals("Si") ? "True" : caso.getAlcohol().equals("No") ? "False" : "" ));
			pw.println("immedRelativeCleft@@@" + (caso.getHermanos().equals("Si") ? "True" : caso.getHermanos().equals("No") ? "False" : "" ));
			pw.println("distRelativeCleft@@@" + (caso.getFamiliar().equals("Si") ? "True" : caso.getFamiliar().equals("No") ? "False" : "" ));
			pw.println("weight@@@" + caso.getPeso());
			pw.println("weightType@@@" + (caso.getTipopeso().equals("Kilogramos") ? "1" : "0"));
			pw.println("beforeSurgery@@@" + (caso.getCirujia().equals("Si") ? "True" : caso.getCirujia().equals("No") ? "False" : "" ));
			pw.println("previousSurgery@@@" + (caso.getAntes().equals("No") ? "" : caso.getTipo().equals("Labio Hendido") ? "1" : caso.getAntes().equals("Paladar Hendido") ? "2" : "3" ));
			pw.println("leftCleftLip@@@" + (caso.getLabioizq().equals("No Hendido") ? "1" : caso.getLabioizq().equals("Completo") ? "2" : "3"));
			pw.println("rightCleftLip@@@" + (caso.getLabioder().equals("No Hendido") ? "1" : caso.getLabioder().equals("Completo") ? "2" : "3"));
			pw.println("leftAlveolus@@@" + (caso.getPaladarizq().equals("No Hendido") ? "1" : caso.getPaladarizq().equals("Completo") ? "2" : caso.getPaladarizq().equals("Submocosa") ? "4" : "3"));
			pw.println("rightAlveolus@@@" + (caso.getPaladarder().equals("No Hendido") ? "1" : caso.getPaladarder().equals("Completo") ? "2" : caso.getPaladarder().equals("Submocosa") ? "4" : "3"));
			pw.println("leftHardCleftPalate@@@" + (caso.getCavidadizq().equals("No Hendido") ? "1" : caso.getCavidadizq().equals("Completo") ? "2" : "3"));
			pw.println("rightHardCleftPalate@@@" + (caso.getCavidadder().equals("No Hendido") ? "1" : caso.getCavidadder().equals("Completo") ? "2" : "3"));
			pw.println("softCleftPalate@@@" + (caso.getSuaveder().equals("No Hendido") ? "1" : caso.getSuaveder().equals("Completo") ? "2" : caso.getSuaveder().equals("Submocosa") ? "4" : "3"));
			pw.println("diagnosisComments@@@" + caso.getComentarios());
			pw.println("diagnosisCommentsLoc@@@");
			pw.println("otherCleft@@@" + (caso.getAntes().equals("Si") ? "True" : caso.getAntes().equals("No") ? "False" : "" ));
			pw.println("veloInsufficiency@@@" + (caso.getDeformidad().equals("Si") ? "True" : caso.getDeformidad().equals("No") ? "False" : "" ));
			pw.println("heart@@@" + (caso.getCorazon().equals("Si") ? "1" : "0"));
			pw.println("urinary@@@" + (caso.getUrinario().equals("Si") ? "1" : "0"));
			pw.println("eyes@@@" + (caso.getOjos().equals("Si") ? "1" : "0"));
			pw.println("nose@@@" + (caso.getNariz().equals("Si") ? "1" : "0"));
			pw.println("ears@@@" + (caso.getOrejas().equals("Si") ? "1" : "0"));
			pw.println("limbs@@@" + (caso.getMiembros().equals("Si") ? "1" : "0"));
			pw.println("fingersToes@@@" + (caso.getDedos().equals("Si") ? "1" : "0"));
			pw.println("skin@@@" + (caso.getPiel().equals("Si") ? "1" : "0"));
			pw.println("tongue@@@" + (caso.getLengua().equals("Si") ? "1" : "0"));
			pw.println("skull@@@" + (caso.getEsqueleto().equals("Si") ? "1" : "0"));
			pw.println("mandible@@@" + (caso.getMandibula().equals("Si") ? "1" : "0"));
			pw.println("speech@@@" + (caso.getHabla().equals("Si") ? "1" : "0"));
			pw.println("growth@@@" + (caso.getCreret().equals("Si") ? "1" : "0"));
			pw.println("mental@@@" + (caso.getRetmen().equals("Si") ? "1" : "0"));
			pw.println("allergies@@@" + (caso.getAlergia().equals("Si") ? "True" : caso.getAlergia().equals("No") ? "False" : "" ));
			pw.println("medAllergies@@@" + caso.getMedicamentos());
			pw.println("medAllergiesLoc@@@");
			pw.println("otherAllergies@@@" + caso.getOtrasalergias());
			pw.println("otherAllergiesLoc@@@");
			pw.println("otherProblems@@@" + caso.getProblemas());
			pw.println("otherProblemsLoc@@@");
			day = caso.getFecha().split("/")[0];
			month = caso.getFecha().split("/")[1];
			year = caso.getFecha().split("/")[2];
			pw.println("evaluationDateDay@@@" + day);
			pw.println("evaluationDateMonth@@@" + month);
			pw.println("evaluationDateYear@@@" + year);
			day = caso.getAdmicion().split("/")[0];
			month = caso.getAdmicion().split("/")[1];
			year = caso.getAdmicion().split("/")[2];
			pw.println("admissionDateDay@@@" + day);
			pw.println("admissionDateMonth@@@" + month);
			pw.println("admissionDateYear@@@" + year);
			day = caso.getFcirujia().split("/")[0];
			month = caso.getFcirujia().split("/")[1];
			year = caso.getFcirujia().split("/")[2];
			pw.println("OperationDateDay@@@" + day);
			pw.println("OperationDateMonth@@@" + month);
			pw.println("OperationDateYear@@@" + year);
			day = caso.getAlta().split("/")[0];
			month = caso.getAlta().split("/")[1];
			year = caso.getAlta().split("/")[2];
			pw.println("dischargeDateDay@@@" + day);
			pw.println("dischargeDateMonth@@@" + month);
			pw.println("dischargeDateYear@@@" + year);
			pw.println("hosSurgeon@@@" + AdminUsuarios.getIDCirujano(caso.getCirujano()));
			pw.println("hosAnesthesiologist@@@" + caso.getAnestesiologo());
			pw.println("hosAnesthesiologistLoc@@@");
			pw.println("anesthMethod@@@" + (caso.getAnestesia().equals("General") ? "0" : "1"));
			String inter = caso.getIntervencionNumerica();
			pw.println("optype0@@@" + (inter.contains("6") ? "alveolarBoneGraft" : "Off"));
			pw.println("optype1@@@" + (inter.contains("5") ? "fistulaRepair" : "Off"));
			pw.println("optype2@@@" + (inter.contains("2") ? "lipNoseRevision" : "Off"));
			pw.println("optype3@@@" + (inter.contains("3") ? "primaryCleftPalate" : "Off"));
			pw.println("optype4@@@" + (inter.contains("1") ? "primaryLipNoseBilateral" : "Off"));
			pw.println("optype5@@@" + (inter.contains("0") ? "primaryLipNoseUnilateral" : "Off"));
			pw.println("optype6@@@" + (inter.contains("4") ? "secondaryCleftPalate" : "Off"));
			pw.println("optype7@@@" + "Off"); //
			pw.println("repairType@@@" + (
					caso.getLabio().equals("Rotación-avance de variantes") ?
						"1" :
						caso.getLabio().equals("Variante triangular") ?
							"2" :
								caso.getLabio().equals("Otro") ?
								"3" : ""
					)); //
			pw.println("commentBox@@@" + caso.getComentariosadi()); 
			pw.println("commentBoxLoc@@@");
			pw.println("complicationInjury@@@"); //
			pw.println("complications@@@" + (caso.getCom().equals("Si") ? "1" : "0")); //
			pw.println("compType1@@@" + (caso.getMuerte().equals("Problemas de Respiración") ? "breathingProblems" : "Off"));
			pw.println("compType2@@@" + (caso.getMuerte().equals("Dehiscencia") ? "dehiscence" : "Off"));
			pw.println("compType4@@@" + (caso.getMuerte().equals("Fístula") ? "fistula" : "Off"));
			pw.println("compType6@@@" + (caso.getMuerte().equals("Vuelta al cuarto de operaciones") ? "backToOR" : "Off"));
			pw.println("version@@@android"); //
			pw.println("fstat@@@" + "1"); //
			pw.println("preFrontal@@@" + ( 
					!caso.getPreFotos().getNameImage1().equals("") ? 
							"photo0.jpg" :  "" ));
			pw.println("preFrontalDescrip@@@");
			pw.println("postFrontal@@@" + ( 
					!caso.getPostFotos().getNameImage1().equals("") ? 
							"photo1.jpg" :  "" ));
			pw.println("postFrontalDescrip@@@");
			pw.println("preWormsEye@@@");
			pw.println("preWormsEyeDescrip@@@");
			pw.println("postWormsEyeDescrip@@@");
			pw.println("preIntra@@@" + ( 
					!caso.getPreFotos().getNameImage2().equals("") ? 
							"photo2.jpg" :  "" ));
			pw.println("preIntraDescrip@@@");
			pw.println("postIntra@@@" + ( 
					!caso.getPostFotos().getNameImage2().equals("") ? 
							"photo3.jpg" :  "" ));
			pw.println("postIntraDescrip@@@");
			pw.println("preCleftSideDescrip@@@");
			pw.println("postCleftSideDescrip@@@");
			pw.println("postSmilingDescrip@@@");
			
			//pw.println("@@@" + caso.get);
			
			res = true;

		} catch (Exception e) {
			error = e.getCause().toString() + e.getMessage();
			res = false;
		} finally {
			try {
				pw.flush();
				pw.close();
				caso.setCsvFile(file);
			} catch(Exception e) {
				error = e.getCause().toString() + e.getMessage();
				res = false;
			}
		}
		
		return res;
	}
	
	public static String getIDSocio(String socio) {
		
		String rSocio = ""; 
		
		try {			
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost postRequest = new HttpPost(Constantes.URL_GET);
			
			MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
			
			reqEntity.addPart("g", new StringBody(Constantes.PARAM_SOCIO));
			reqEntity.addPart("v", new StringBody(socio));
			
			postRequest.setEntity(reqEntity);
			
			String sResponse;
			
			HttpResponse response = httpClient.execute(postRequest);
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "UTF-8"));
			
			sResponse = reader.readLine();
			
			if(sResponse != null && sResponse.trim().startsWith(Constantes.RESPUESTA_ENVIO_CORRECTO)){
				String[] res = sResponse.split(",");
				
				if(res != null && res.length == 2)
					rSocio = res[1];
			}
			
			//error = "Server:" + sResponse;

		} catch (Exception e) {
			error = e.getCause().getMessage() + " - " + e.getMessage();
		}
		
		return rSocio;
	}
	
	public static String getIDHospital(String hospital) {
		
		String rHospital = ""; 
		
		try {			
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost postRequest = new HttpPost(Constantes.URL_GET);
			
			MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
			
			reqEntity.addPart("g", new StringBody(Constantes.PARAM_HOSPITAL));
			reqEntity.addPart("v", new StringBody(hospital));
			
			postRequest.setEntity(reqEntity);
			
			String sResponse;
			
			HttpResponse response = httpClient.execute(postRequest);
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "UTF-8"));
			
			sResponse = reader.readLine();
			
			if(sResponse != null && sResponse.trim().startsWith(Constantes.RESPUESTA_ENVIO_CORRECTO)){
				String[] res = sResponse.split(",");
				
				if(res != null && res.length == 2)
					rHospital = res[1];
			}
			
			//error = "Server:" + sResponse;

		} catch (Exception e) {
			error = e.getCause().getMessage() + " - " + e.getMessage();
		}
		
		return rHospital;
	}
	
	public static String getIDCirujano(String cirujano) {
	
		String rCirujano = ""; 
		
		try {			
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost postRequest = new HttpPost(Constantes.URL_GET);
			
			MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
			
			reqEntity.addPart("g", new StringBody(Constantes.PARAM_CIRUJANO));
			reqEntity.addPart("v", new StringBody(cirujano));
			
			postRequest.setEntity(reqEntity);
			
			String sResponse;
			
			HttpResponse response = httpClient.execute(postRequest);
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "UTF-8"));
			
			sResponse = reader.readLine();
			
			if(sResponse != null && sResponse.trim().startsWith(Constantes.RESPUESTA_ENVIO_CORRECTO)){
				String[] res = sResponse.split(",");
				
				if(res != null && res.length == 2)
					rCirujano = res[1];
			}
			
			//error = "Server:" + sResponse;

		} catch (Exception e) {
			error = e.getCause().getMessage() + " - " + e.getMessage();
		}
		
		return rCirujano;
	}
	
	public static String fillZeros(int num) {
		return ((num >= 0 && num <= 9) ? "0" : "") + num;
	}
	
	public static String error = "";

}
